//
//  SqlHelper.m
//  joke
//
//  Created by liwei on 15/12/13.
//  Copyright © 2015年 liwei. All rights reserved.
//

#import "SqlHelper.h"

#define DBVERSION @"DBVERSION"
#define VERSIONNUMBER @"VERSIONNUMBER"

@interface SqlHelper () {
    NSString *_dbFile;
    NSArray *sqls;
}

@end

@implementation SqlHelper

- (instancetype)initWithDBFilePath:(NSString *)filePath AndSQLPlist:(NSString *)plist {
    if (self = [super init]) {
        _dbFile = filePath;
        sqls = [[NSArray alloc] initWithContentsOfFile:plist];
        _dbQueue = [FMDatabaseQueue databaseQueueWithPath:_dbFile];
        [self checkAndUpdateDB];
    }
    return self;
}

- (void) checkAndUpdateDB {
    [_dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        FMResultSet *rs = [db executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", DBVERSION];
        if ([rs next]) {
            NSInteger count = [rs intForColumn:@"count"];
            
            int currentVersion = 0;
            
            if (count == 0) {   //没有创建VERSION表
                if (![db executeUpdate:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (%@ INTEGER);", DBVERSION, VERSIONNUMBER]]) {
                    *rollback = YES;
                    return;
                }
                if (![db executeUpdate:[NSString stringWithFormat:@"INSERT INTO %@ (%@) VALUES (%ld)", DBVERSION, VERSIONNUMBER, sqls.count]]) {
                    *rollback = YES;
                    return;
                }
                currentVersion = 0;
            } else {
                FMResultSet *frs = [db executeQuery:[NSString stringWithFormat:@"select %@ from %@", VERSIONNUMBER, DBVERSION]];
                if ([frs next]) {
                    currentVersion = [frs intForColumn:VERSIONNUMBER];
                }
                [frs close];
                if (![db executeUpdate:[NSString stringWithFormat:@"UPDATE %@ set %@=%ld", DBVERSION, VERSIONNUMBER, sqls.count]]) {
                    *rollback = YES;
                    return;
                }
            }
            
            for (int i = currentVersion; i < sqls.count; i++) {
                NSArray *array = sqls[i];
                for (NSString *sql in array) {
                    if (![db executeUpdate:sql]) {
                        *rollback = YES;
                        return;
                    }
                }
            }
        }
        [rs close];
    }];
    [_dbQueue close];
}



@end
